// schedule.js
const scheduleApp = createApp({
    data() {
        return {
            schedules: [],
            teachers: [],
            courses: [],
            classes: [],
            formDataClass: '', // 课程安排班级代码，复合值
            loading: false,
            error: null,
            formData: {
                teacherUserNo: '',  // 教师工号
                courseId: '',     // 课程ID
                semester: '',     // 学期
                classCode: '',      // 课程安排班级代码
                majorCode: '',      // 课程安排专业代码
                collegeCode: '',      // 课程安排学院代码
            }
        }
    },
    methods: {
        // 加载课程安排数据
        async loadSchedules() {
            this.loading = true;
            this.error = null;
            try {
                const response = await fetch(window.contextPath+'/schedule/listAll');
                const teachersResponse = await fetch(window.contextPath+'/teacher/listAll');
                const coursesResponse = await fetch(window.contextPath+'/course/listAll');
                const classesResponse = await fetch(window.contextPath+'/class/listAll');
                if (response.ok && teachersResponse.ok && coursesResponse.ok && classesResponse.ok) {
                    this.schedules = await response.json();
                    this.teachers = await teachersResponse.json();
                    this.courses = await coursesResponse.json();
                    this.classes = await classesResponse.json();
                } else {
                    const errorText = await response.text();
                    this.error = '加载数据失败,错误码:'+ response.status +',错误信息: ' + errorText
                    showErrorModal(this.error)
                }
            }catch ( error) {
                this.error = '网络错误: ' + error.message;
                showErrorModal(this.error)
            }finally {
                this.loading = false;
            }
        },
        // 添加课程安排信息
        async addSchedule() {
            const clazz = this.formDataClass.split('-');
            // 处理 classCode、majorCode、collegeCode,便于后端接收
            this.formData.classCode = clazz[0];
            this.formData.majorCode = clazz[1];
            this.formData.collegeCode = clazz[2];
            console.log(this.formData);
            try {
                console.log(this.formData);
                const response = await fetch(window.contextPath+'/schedule/add', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    // 处理 classCode、majorCode、collegeCode
                    body: JSON.stringify(this.formData)
                });

                if (response.ok) {
                    alert('添加成功')
                    await this.loadSchedules();
                    this.formDataClass = '';
                    this.formData = {
                        teacherUserNo: '',  // 教师工号
                        courseId: '',     // 课程ID
                        semester: '',     // 学期
                        classCode: '',      // 课程安排班级代码
                        majorCode: '',      // 课程安排专业代码
                        collegeCode: '',      // 课程安排学院代码
                    };
                    closeScheduleAddModal();
                } else {
                    const errorText = await response.text();
                    this.error = '添加课程安排信息失败,错误码:'+ response.status +',错误信息: ' + errorText
                    showErrorModal(this.error)
                }
            } catch (error) {
                this.error = '网络错误: ' + error.message;
                showErrorModal(this.error)
            }
        },
        // 删除课程安排信息
        async deleteSchedule(scheduleId) {
            try {
                if (!confirm('确定要删除该课程安排信息吗？')) {
                    return;
                }

                const response = await fetch(window.contextPath+'/schedule/delete?scheduleId=' + scheduleId, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    alert('删除成功')
                    await this.loadSchedules();
                } else {
                    const errorText = await response.text();
                    this.error = '删除课程安排失败,错误码:'+ response.status +',错误信息: ' + errorText
                    showErrorModal(this.error)
                }
            } catch (error) {
                this.error = '网络错误: ' + error.message;
                showErrorModal(this.error)
            }
        },
        // 修改课程安排信息
        async updateSchedule() {
            alert('该功能正在开发中...')
        },

        // 当选择专业时，自动更新学院代码
        updateCollegeCode() {
            if (this.formData.majorCode) {
                // 查找选中的专业对象
                const selectedMajor = this.majors.find(major => major.majorCode === this.formData.majorCode);
                if (selectedMajor) {
                    // 更新 formData 中的 collegeCode
                    this.formData.collegeCode = selectedMajor.collegeCode;
                }
            } else {
                // 如果未选择专业，则清空学院代码
                this.formData.collegeCode = '';
            }
        }
    },
    mounted() {
        window.scheduleAppInstance = this;
    }
});
scheduleApp.mount('#schedule-content');

// 显示添加课程安排表单
function showScheduleAddModal() {
    const modal = document.getElementById('scheduleAddModal');
    modal.classList.add('show');
    modal.style.display = 'flex';
}

// 关闭添加课程安排表单
function closeScheduleAddModal() {
    document.getElementById('scheduleAddModal').style.display = 'none';
}
